<?php

/**
 * @author: biggege
 * @since:  2021-11-09 14:51:11
 */
namespace App\Http\Controllers;

use Storage;
use App\Models\File;
use App\Models\FileMapping;
use App\Repositories\FileRepository;
use Illuminate\Http\Request;
use App\Repositories\MicrosoftBlobRepository;

class EditorController extends BaseController
{
    public $fileRepo;

    public function __construct()
    {
        $this->fileRepo = new FileRepository();
    }

    public function imgUpload(Request $request)
    {
        ini_set('memory_limit', '1024M');
        set_time_limit(0);

        $userLogin = login_user();

        if (!login_user()) {
            return response([
                'code' => 401,
                'msg' => '权限不足',
                'data' => []
            ], 401);
        }

        $result = [];

        if(!empty($request['source'])) {
            $ctx = stream_context_create(array('http'=>
                array('timeout' => 30)
            ));

            foreach ($request['source'] as $key => $val) {
                if(strpos($val, env('AZURE_DOMAIN')) === false) {
                    $imgData = getimagesize($val);
                    if($imgData == false) {
                        continue;
                    }
                    $data = file_get_contents($val, false, $ctx);
                    $file = [];
                    $file['md5'] = md5_file($val);
                    $file['sha1'] = sha1_file($val);
                    $file['name'] = $val;
                    $file['size'] =  ceil(strlen($data)/1024);
                    $file['mimetype'] = $imgData['mime'];
                    $file['ext'] = substr($imgData['mime'], strripos($imgData['mime'], "/") + 1);
                    $file['location'] = config('filesystems.disks.azure.driver');
                    $ff = File::query()->where('md5', $file['md5'])->first();
                    if (!$ff) {
                        $filename = config('filesystems.disks.azure.file_dir') .'/'. date('Ym') .'/'. $file['md5'] . '.' . $file['ext'];
                        
                        $res = app(MicrosoftBlobRepository::class)->upload($val, $filename);

                        if($res != true) {
                            continue;
                        }

                        $file['created_at'] = date('Y-m-d H:i:s');
                        $file['source'] = '';
                        $file['create_user_id'] = $userLogin['id'];
                        $file['create_user_name'] = $userLogin['username'];
                        $file['path'] = '/' . config('filesystems.disks.azure.container_name') . '/' . $filename;
                        $file_id = File::query()->insertGetId($file);
                    }else{
                        $file_id = $ff['id'];
                        if ($ff['deleted_at']) {
                            File::withTrashed()->where('id', $file_id)->update(['deleted_at' => null]);
                        }
                        if ($ff['name'] !== $val) {
                            // 同样的文件，文件名不一样，更新成新名字
                            File::query()->where('id', $file_id)->update(['name' => $val]);
                        }
                        $file = $ff;
                    }

                    $result[] = [
                        'source' => $val,
                        'full_path' => getPreviewImage(image_path($file['path']))
                    ];
                }
            }
        }

        return response()->json($result);
    }

}